<template>
    <div class="add-to-favorite">
        <div class="title">添加到收藏夹</div>
        <div class="content">
            <div class="group-list">
                <ul>
                    <li :class="currSelected.has(item.fid) ? 'selected' : ''" @click="selectOrCancel(item.fid)"
                        v-for="(item, index) in favorites" :key="index">
                        <label>
                            <span class="select-box">
                                <i class="iconfont icon-gou"></i>
                            </span>
                            <span :title="item.title" class="fav-title">{{ item.title }}</span>
                            <span class="count">{{ item.count }}{{ item.type === 1 ? "" : "/1000" }}</span>
                        </label>
                    </li>
                    <div class="collection-mask" v-if="isCreating"></div>
                </ul>
                <div class="add-group" ref="addGroup">
                    <div class="add-btn" v-if="!isCreating" @click="(e) => startCreating(e)"><i
                            class="iconfont icon-jia"></i>新建收藏夹</div>
                    <div class="input-group" v-else>
                        <input type="text" v-model="input" maxlength="20" placeholder="最多输入20个字">
                        <button class="create-btn" @click="create">新建</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="bottom">
            <button class="submit" ref="submitBtn" :class="{ 'disable': isCreating || areSetsEqual }"
                @click="submit">确定</button>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/store/user';
import { addFavorite } from '@/api/favorite';
import { collectVideo } from '@/api/favorite';

// Props
const props = defineProps({
    lastSelected: {
        type: Set,
        default: () => new Set(),
    },
    vid: {
        type: Number,
        default: 0,
    }
});

// 本地状态
const favorites = ref([]); // 收藏夹列表
const currSelected = ref(new Set()); // 当前选中的收藏夹ID集合
const isCreating = ref(false); // 是否正在创建收藏夹
const input = ref(""); // 新建收藏夹名字

const userStore = useUserStore();

// 计算属性：判断当前选中的收藏夹集合与原先选择的是否相同
const areSetsEqual = computed(() => {
    if (props.lastSelected.size !== currSelected.value.size) {
        return false;
    }
    return Array.from(props.lastSelected).every(value => currSelected.value.has(value));
});

// 监听 Pinia 中收藏夹的变化
watch(
    () => userStore.favorites,
    (curr) => {
        favorites.value = JSON.parse(JSON.stringify(curr));
        // console.log("监听到vuex的收藏夹列表变化: ", favorites.value);
    },
    { deep: true }
);

// 创建新收藏夹的函数
const create = async () => {
    if (input.value.length === 0) {
        ElMessage.error("请输入收藏夹名字");
        return;
    }
    const formData = new FormData();
    formData.append("title", input.value); // 设置新收藏夹的标题
    formData.append("desc", ""); // 设置新收藏夹的描述
    formData.append("visible", 1); // 设置新收藏夹为公开

    await addFavorite(formData).then(res => {
        if (res.code == 1) {
            // 初始化已选的收藏夹，避免收藏夹数量不一致
            currSelected.value = new Set([...props.lastSelected]);
            // 将新创建的收藏夹插入到 Pinia 中的收藏夹列表
            userStore.addFavorite(res.data);
            input.value = ""; // 清空输入框
            isCreating.value = false; // 关闭创建收藏夹的状态
        } else {
            return;
        }
    });
};

const emit = defineEmits(["collected"]);

// 提交添加/移除收藏夹的函数
const submit = async () => {
    // 如果选择的收藏夹没有变化，则不做提交
    if (areSetsEqual.value) return;

    if (props.vid === 0) {
        ElMessage.error("视频不存在");
        return;
    }

    // 获取需要移除和需要添加的收藏夹ID集合
    const remove = Array.from(props.lastSelected).filter(value => !currSelected.value.has(value));
    const add = Array.from(currSelected.value).filter(value => !props.lastSelected.has(value));

    // 判断是否是收藏状态变化
    const isCollect = props.lastSelected.size === 0 && add.length > 0; // 如果之前没有收藏，现在有收藏夹加入，则是收藏操作
    const isCancel = add.length === 0 && props.lastSelected.size > 0 && props.lastSelected.size === remove.length && remove.every(value => props.lastSelected.has(value)); // 如果没有新加入的收藏夹，且之前有收藏，表示取消收藏

    // const formData = new FormData();
    // formData.append("vid", Number(props.vid)); // 添加视频ID
    // formData.append("adds", add.join(',')); // 添加的收藏夹ID
    // formData.append("removes", remove.join(',')); // 移除的收藏夹ID

    console.log("提交收藏夹操作: ", props.vid);

    // 发起请求，提交添加/移除收藏夹操作
    await collectVideo(props.vid, add.join(','), remove.join(',')).then(res => {
        if (res.code == 1) {
            // 根据操作状态更新 Pinia 中的视频收藏状态
            if (isCollect) {
                userStore.attitudeToVideo.collect = true;
            } else if (isCancel) {
                userStore.attitudeToVideo.collect = false;
            }
            // 提交后更新收藏夹列表
            const info = {
                fids: currSelected.value,
                num: isCollect ? 1 : isCancel ? -1 : 0, // 如果是收藏操作，增加数量；如果是取消收藏，减少数量
            };

            // 更新 Pinia store 中的收藏夹信息
            userStore.updateFavorites(favorites.value);

            // 触发父组件事件，通知收藏夹更新
            emit("collected", info);
        } else {
            return;
        }
    });
};

// 选择或取消选择收藏夹
const selectOrCancel = (fid) => {
    let favItem = favorites.value.find(item => item.fid === fid);
    if (currSelected.value.has(fid)) {
        currSelected.value.delete(fid); // 如果已选择，则取消选择
        favItem.count--;
    } else {
        currSelected.value.add(fid); // 如果未选择，则添加到选择集合
        favItem.count++;
    }
};

// 开始创建收藏夹
const startCreating = (event) => {
    isCreating.value = true; // 设置正在创建的状态
    event.stopPropagation();
};

const addGroup = ref(null);
const submitBtn = ref(null);

// 点击空白区域关闭创建收藏夹输入框
const handleOutsideClick = (event) => {
    if (!addGroup.value.contains(event.target) && !submitBtn.value.contains(event.target)) {
        isCreating.value = false; // 关闭创建收藏夹的状态
    }
};

// 生命周期钩子
onMounted(() => {
    // console.log("aaaaaaaaaaa" + JSON.stringify(userStore.favorites));
    favorites.value = userStore.favorites;
    window.addEventListener("click", handleOutsideClick); // 监听点击空白区域事件
});

onBeforeUnmount(() => {
    window.removeEventListener("click", handleOutsideClick); // 移除事件监听
});

</script>

<style scoped>
.add-to-favorite {
    width: 420px;
    border-radius: 4px;
    background: #FFFFFF;
    overflow: hidden;
}

.title {
    position: relative;
    padding: 0 20px;
    height: 50px;
    line-height: 50px;
    font-size: 16px;
    color: var(--text1);
    border-bottom: var(--line_regular);
    text-align: center;
}

.content {
    padding: 0 36px;
    height: 300px;
    overflow: auto;
}

.group-list {
    max-height: 300px;
    padding-bottom: 14px;
}

ol,
ul {
    list-style: none;
}

.group-list ul {
    position: relative;
    margin-top: 24px;
    min-height: 210px;
}

.group-list li {
    padding-bottom: 24px;
    font-size: 14px;
    color: var(--text1);
    cursor: pointer;
}

.group-list li:hover {
    color: var(--brand_pink);
}

.group-list li label {
    cursor: pointer;
    display: block;
}

.group-list li .select-box {
    position: relative;
    display: inline-flex;
    width: 20px;
    height: 20px;
    border: 2px solid #ccc;
    border-radius: 3px;
    align-items: center;
    justify-content: center;
    margin-right: 18px;
    vertical-align: middle;
}

.group-list li:hover .select-box {
    border: 2px solid var(--brand_pink);
}

.selected .select-box {
    background-color: var(--brand_pink);
    border: 1px solid var(--brand_pink) !important;
}

.icon-gou {
    color: #fff;
    font-size: 25px;
    transform: translateX(0.5px);
}

.fav-title {
    max-width: 220px;
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: middle;
    line-height: 20px;
}

.selected .fav-title {
    color: var(--brand_pink);
}

.count {
    float: right;
    color: var(--text2);
    font-size: 12px;
    line-height: 18px;
}

.collection-mask {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    opacity: 0.5;
    background: #FFFFFF;
    background: var(--bg1_float);
}

.add-group {
    margin-bottom: 5px;
    width: 348px;
}

.add-btn {
    height: 34px;
    line-height: 34px;
    border: 1px solid var(--text3);
    border-radius: 4px;
    font-size: 12px;
    color: var(--text2);
    cursor: pointer;
    box-sizing: unset;
}

.add-btn:hover {
    border: 1px solid var(--brand_pink);
}

.icon-jia {
    margin: 0 10px;
}

.input-group {
    height: 34px;
    line-height: 34px;
    border: 1px solid var(--brand_pink);
    border-radius: 4px;
    position: relative;
    box-sizing: unset;
}

.input-group input {
    border: none;
    font-size: 12px;
    width: 200px;
    margin-left: 10px;
    padding: 0;
    box-shadow: none;
    height: 100%;
    background: transparent;
    color: var(--text1);
    outline: none;
}

.input-group .create-btn {
    float: right;
    height: 34px;
    width: 90px;
    background: var(--Pi1);
    border: none;
    border-left: 1px solid var(--brand_pink);
    border-radius: 0 4px 4px 0;
    font-size: 14px;
    color: var(--brand_pink);
    cursor: pointer;
}

.bottom {
    height: 76px;
    text-align: center;
    margin: 0 36px;
    border-top: 1px solid var(--line_regular);
}

.submit {
    font-size: 14px;
    width: 160px;
    height: 40px;
    margin-top: 18px;
    background: var(--brand_pink);
    border: none;
    border-radius: 4px;
    color: #fff;
    cursor: pointer;
}

.submit:hover {
    background: var(--Pi4);
}

.submit.disable {
    background-color: var(--graph_bg_thick);
    color: var(--text3);
}
</style>